package com.nononsenseapps.feeder.ui.common.htmlview

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import java.util.regex.Matcher
import java.util.regex.Pattern

object TextViewSpanHelper {
    fun getHighLightWordsArray(originString:String, keyWords:List<String>, highLightColor : Int, basePosition : Int = 0,endPosition : Int=originString.length) : SpannableString {
        val subStringToMatcher=originString.subSequence(basePosition,endPosition)
        val originSpannableString = SpannableString(originString)
        var matcher: Matcher
        keyWords.forEach {
            matcher = Pattern.compile(it).matcher(subStringToMatcher)
            while (matcher.find()) {
                originSpannableString.setSpan( ForegroundColorSpan(highLightColor),  basePosition+matcher.start(), basePosition+ matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }
        return originSpannableString
    }

    fun buildHighLightWithWordsArray(originString:String, keyWords:List<String>, highLightColor : Int, basePosition : Int = 0,endPosition : Int=originString.length,originSpannableStringBuilder: SensibleSpannableStringBuilder)  {
        val subStringToMatcher=originString.subSequence(basePosition,endPosition)
        var matcher: Matcher
        keyWords.forEach {
            matcher = Pattern.compile(it).matcher(subStringToMatcher)
            while (matcher.find()) {
                originSpannableStringBuilder.setSpan( ForegroundColorSpan(highLightColor),  basePosition+matcher.start(), basePosition+ matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }
    }
}